<?php 

/**
* 
*/
//2017-07-24自练习
class Modeln
{	
	public $table;
	public static $db;
	public $error;
	public $errno;
	public $where;
	function __construct($table=null)
	{	

		if ($table) {
			$this->table = $table;
		}
		if (!self::$db) {
			var_dump($table);
			try{
			self::$db = new PDO("mysql:host=".C('db_host').";dbname=".C('db_dbname').";charset=utf8",C('db_user'),C('db_password'));
			}catch(PDOException  $e ){
				echo "Error: ".$e;exit;
			}
		}
		
	}

	public function add($data)
	{	
		//implode()  返回由数组(的值)元素组合成的字符串 
		$values = implode("','", $data);
		$keys = implode(',',array_keys($data));   //取到的所有键放入一个数组
		// var_dump($data);
		// var_dump($keys);
		$sql = "insert into ".$this->table." (".$keys.") values ('".$values."')";
		//var_dump($sql);

		return $this->exec($sql);
	}

	public function exec($sql)
	{
		$res = self::$db->exec($sql);
		if (!$res) {
			$this->errno = self::$db->errorCode();
			$this->error = self::$db->errorInfo()[2];
		}
		//var_dump($this->errno,$this->error);
		return $res;
	}

	public function query($sql)
	{
		$res = self::$db->query($sql);
		if (!$res) {
			$this->errno = self::$db->errorCode();
			$this->error = self::$db->errorInfo()[2];
			return false;
		}
		//var_dump($res);exit;
		return $res->fetchAll(PDO::FETCH_ASSOC);
	}

	public function getError()
	{
		return "错误代码: ".$this->errno.", 错误信息: ".$this->error;
	}

	public function where($where)
	{
		$this->where = " where ".$where;

		//连贯操作
		return $this;
	}

	public function find()
	{
		$sql = "select * from ".$this->table.$this->where;//$this->where变量,当有执行where查询时才有数据
		//var_dump($sql);
		return $this->query($sql);
	}

	public function save($data)
	{	
		$str = ' ';
		foreach ($data as $k => $v) {
			$str .= $k.' = "'.$v.'",';
		}
		$str = rtrim($str,',');

		//var_dump($str);
		$sql = "update ".$this->table." set".$str.$this->where;
		//var_dump($sql);
		return $this->exec($sql);
	}

	public function delete($id=null)
	{	
		$key = $this->getPri();
		//var_dump($key);
		if ($id) {
			$sql = "delete from ".$this->table." where ".$key."=".$id;
		}else{
			$sql = "delete from ".$this->table.$this->where;
		}
		//var_dump($sql);
		return $this->exec($sql);
	}

	public function getPri()
	{	
		$sql = "desc ".$this->table;
		$res = $this->query($sql);
		//var_dump($res);
		foreach ($res as $v) {
			if ($v['Key']=='PRI') {
				return $v['Field'];
			}
		}
	}


}




















 ?>